package com.lanhai.javaBean;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.lanhai.Main;
import com.lanhai.model.Guidepost;
import com.lanhai.utils.RegionUtil;
import com.mybatis.dao.GuidepostDao;

public class GuidepostBean {

	/**
	 * 加载地标列表
	 */
	public static List<Guidepost> loadData(SqlSessionFactory sqlSessionFactory){
		List<Guidepost> guidepostList = new ArrayList<Guidepost>();
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
			GuidepostDao gpDao = sqlSession.getMapper(GuidepostDao.class);
			List<Map<String, Object>> list = gpDao.selectAll();
			if(list.size() > 0){
				for(Map<String, Object> m:list){
					Guidepost gd = new Guidepost();
					gd.setId((Integer)m.get("id"));
					gd.setName((String)m.get("name"));//名称
					gd.setNum((Integer)m.get("num"));//地标号
					gd.setType((Integer)m.get("type"));//类型
//					gd.setSubType((Integer)m.get("subtype"));//子类
//					gd.setAgvState((Integer)m.get("agvstate"));//对应的AGV状态
//					gd.setCaId((Integer)m.get("caId"));//主交管区ID
					gd.setCtrlIp((String)m.get("ctrlIp"));//所属调度的IP地址
					gd.setStep((Integer)m.get("step"));//工序
					gd.setNextStep((Integer)m.get("nextStep"));//下一道工序
//					gd.setParkId((Integer)m.get("parkId"));//站点ID
					gd.setMapX((Integer)m.get("mapX"));//地图X座标
					gd.setMapY((Integer)m.get("mapY"));//地图Y座标
					gd.setXzdNumItem((Integer)m.get("xzdNumItem"));//
					String cdIds = (String)m.get("controlAreaIds");//对应交管区ID
					if(cdIds != null){
						String[] cdIdArr = cdIds.split(",");
						if(cdIdArr.length > 0){
							int[] cids = new int[cdIdArr.length];
							for(int i = 0; i < cdIdArr.length; i++){
								if(!cdIdArr[i].equals("")){
									cids[i] = Integer.parseInt(cdIdArr[i]);
								}
							}
							gd.setControlAreaIds(cids);
						}
					}
					String acaIds = (String)m.get("aheadCaIds");//前方交管区ID
					if(acaIds != null){
						String[] acaIdArr = acaIds.split(",");
						if(acaIdArr.length > 0){
							int[] cids = new int[acaIdArr.length];
							for(int i = 0; i < acaIdArr.length; i++){
								cids[i] = Integer.parseInt(acaIdArr[i]);
							}
							gd.setAheadCaIds(cids);
						}
					}
					guidepostList.add(gd);					
				}
			}
	    }catch(Exception e){
	    	e.printStackTrace();
	    }finally{
	    	sqlSession.close();
	    }
		return guidepostList;
	}
	
	/**
	 * 判断当前座标是否在某个站点的半径范围内
	 * @param parkList
	 * @param currentX
	 * @param currentY
	 * @param radius
	 */
	public static Guidepost contrast(Map<Integer, Guidepost> guidepostMap, double currentX, double currentY
			, double radius){
		Guidepost gp = null;
		for(Map.Entry<Integer, Guidepost> map:guidepostMap.entrySet()){
			Guidepost guidepost = map.getValue();
			double distance = RegionUtil.distance(guidepost.getMapX(), guidepost.getMapY(), currentX, currentY);
			if(distance <= radius){
				gp = guidepost;
				break;
			}
		}
		return gp;
	}
	
	public static void updateSlamPoint(SqlSessionFactory sqlSessionFactory){
		SqlSession sqlSession = sqlSessionFactory.openSession();//获取sqlsession对象。
		
		try {
        	//InputStream is = ChargerBean.class.getClass().getResourceAsStream("/data/agvList.csv"); 
        	//BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        	String filePath = "d:/agvData/slam_point.csv";//文件路径。
        	BufferedReader reader = new BufferedReader(new FileReader(filePath));//换成你的文件名,从文件中输入数据
            reader.readLine();//第一行信息，为标题信息，不用，如果需要，注释掉  readLine()方法是阻塞式的, 如果到达流末尾, 就返回null，readLine()只有在数据流发生异常或者另一端被close()掉时，才会返回null值。
            String line = null;//line：线
			GuidepostDao dao = sqlSession.getMapper(GuidepostDao.class);//通过 SqlSession 的 getMapper 方法来获取一个 Mapper 接口
            while((line=reader.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件，这里根据逗号切分
                int mapX = Integer.parseInt(item[1]) / 10;//Integer.parseInt把当前String对象转成int
                int mapY = Integer.parseInt(item[2]) / 10;
                //if(mapX > 0 && mapY > 0){
                	int num = Integer.parseInt(item[0]);
                	Map<String, Integer> map = new HashMap<String, Integer>();
                	map.put("num", num);
                	map.put("mapX", mapX);
                	map.put("mapY", mapY);
        			dao.updateSlamPoint(map);
        			sqlSession.commit();                	
                	//System.out.println("num:" + item[0] + ",x:" + item[1] + "[" + mapX + "]" + ",y:" + item[2]);
                //}
            } 
            reader.close();				
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally {
	    	sqlSession.close();
	    }
	}
	
	public static void insertSlamPoint(SqlSessionFactory sqlSessionFactory){
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
        	//InputStream is = ChargerBean.class.getClass().getResourceAsStream("/data/agvList.csv"); 
        	//BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        	String filePath = "d:/agvData/slam_point.csv";
        	BufferedReader reader = new BufferedReader(new FileReader(filePath));//换成你的文件名
            reader.readLine();//第一行信息，为标题信息，不用，如果需要，注释掉
            String line = null;
			GuidepostDao dao = sqlSession.getMapper(GuidepostDao.class);
            while((line=reader.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件，这里根据逗号切分
                int mapX = Integer.parseInt(item[1]) / 10;
                int mapY = Integer.parseInt(item[2]) / 10;
                //if(mapX > 0 && mapY > 0){
                	int num = Integer.parseInt(item[0]);
                	Map<String, Integer> map = new HashMap<String, Integer>();
                	map.put("num", num);
                	map.put("mapX", mapX);
                	map.put("mapY", mapY);
        			dao.insertSlamPoint(map);
        			sqlSession.commit();                	
                	//System.out.println("num:" + item[0] + ",x:" + item[1] + "[" + mapX + "]" + ",y:" + item[2]);
                //}
            } 
            reader.close();				
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally {
	    	sqlSession.close();
	    }
	}
	
	/**
	 * 更新数据库地标
	 * @param sqlSessionFactory
	 */
	public static void insertOfUpdateSlamPoint(SqlSessionFactory sqlSessionFactory,Main main){
		SqlSession sqlSession = sqlSessionFactory.openSession();
		try {
        	//InputStream is = ChargerBean.class.getClass().getResourceAsStream("/data/agvList.csv"); 
        	//BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        	String filePath = "d:/agvData/slam_point.csv";
        	BufferedReader reader = new BufferedReader(new FileReader(filePath));//换成你的文件名
            reader.readLine();//第一行信息，为标题信息，不用，如果需要，注释掉
            String line = null;
			GuidepostDao dao = sqlSession.getMapper(GuidepostDao.class);
            while((line=reader.readLine())!=null){
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件，这里根据逗号切分
                if(item.length > 0) {
                	int mapX = Integer.parseInt(item[1]) / 10;
                	int mapY = Integer.parseInt(item[2]) / 10;
                	//if(mapX > 0 && mapY > 0){
                	int num = Integer.parseInt(item[0]);
                	Map<String, Integer> map = new HashMap<String, Integer>();
                	map.put("num", num);
                	map.put("mapX", mapX);
                	map.put("mapY", mapY);
                	boolean updateFlag = false;
                	for (Map.Entry<Integer,Guidepost> m : main.guidepostMap.entrySet()) {
						if(m.getValue().getNum() == num) {
							updateFlag = true;
						}
					}
                	//更新地标数据表
                	if(updateFlag) {
                		dao.updateSlamPoint(map);
                	}else {
                		dao.insertSlamPoint(map);                		
                	}
                	sqlSession.commit();                	             	
                }
                	//System.out.println("num:" + item[0] + ",x:" + item[1] + "[" + mapX + "]" + ",y:" + item[2]);
                //}
            } 
            reader.close();				
        } catch (Exception e) { 
            e.printStackTrace(); 
        } finally {
	    	sqlSession.close();
	    }
	}
	
}
